<template>
  <div class="hospital-form-container">
    <!-- 页面标题 -->
    <h2 class="page-title">医院信息录入</h2>

    <el-form :model="form" label-width="120px" label-position="top">
      <!-- 医院名称 -->
      <el-form-item label="医院名称：" required>
        <el-input v-model="form.name" placeholder="请输入医院名称" clearable />
      </el-form-item>

      <!-- 医院头像 -->
      <el-form-item label="医院头像：">
        <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <el-avatar v-if="form.logo" :src="form.logo" :size="120" />
          <div v-else class="upload-area">
            <el-icon><Plus /></el-icon>
            <div class="upload-text">上传头像</div>
            <div class="upload-hint">支持格式：jpg、png、jpeg</div>
          </div>
        </el-upload>
      </el-form-item>

      <!-- 医院地址 -->
      <el-form-item label="医院地址：" required>
        <div class="address-select">
          <el-select v-model="form.address" placeholder="请选择地址" clearable>
            <el-option
                v-for="item in address1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
          <div class="address-select">
          <el-select v-model="form.branchAddress" placeholder="请选择详细地址" clearable>
            <el-option
                v-for="item in branchAddress1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
      </el-form-item>

      <!-- 医院类型和等级 -->
      <div class="form-row">
        <el-form-item label="医院类型：" required>
          <el-select v-model="form.type" placeholder="请选择" clearable>
            <el-option
                v-for="item in hospitalTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="医院等级：" required>
          <el-select v-model="form.level" placeholder="请选择" clearable>
            <el-option
                v-for="item in hospitalLevels"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </div>

      <!-- 医院科室 -->
      <el-form-item label="医院科室：" required>
        <div class="department-select">
          <div class="department-level">
            <div class="level-header">
              <span>一级科室</span>
              <el-checkbox v-model="allPrimarySelected" @change="selectAllPrimary">
                全选
              </el-checkbox>
              <span class="selected-count">已选择 {{ selectedPrimaryCount }}项/共{{ primaryDepartments.length }}项</span>
            </div>
            <el-checkbox-group v-model="form.primaryDepartments">
              <el-checkbox
                  v-for="dept in primaryDepartments"
                  :key="dept.value"
                  :label="dept.label"
                  @change="updatePrimarySelection"
              />
            </el-checkbox-group>
          </div>

          <div class="department-level">
            <div class="level-header">
              <span>二级科室</span>
              <el-checkbox v-model="allSecondarySelected" @change="selectAllSecondary">
                全选
              </el-checkbox>
              <span class="selected-count">已选择 {{ selectedSecondaryCount }}条/共{{ secondaryDepartments.length }}条</span>
            </div>
            <el-checkbox-group v-model="form.secondaryDepartments">
              <el-checkbox
                  v-for="dept in secondaryDepartments"
                  :key="dept.value"
                  :label="dept.label"
                  @change="updateSecondarySelection"
              />
            </el-checkbox-group>
          </div>
        </div>

        <!-- 已选择科室展示 -->
        <div class="selected-departments" v-if="form.primaryDepartments.length > 0">
          <div class="selected-title">已选择科室</div>
          <div v-for="primary in form.primaryDepartments" :key="primary">
            {{ primary }}：
            <span v-for="(secondary, index) in getSecondariesByPrimary(primary)" :key="secondary">
              {{ secondary }}{{ index < getSecondariesByPrimary(primary).length - 1 ? '、' : '' }}
            </span>
          </div>
        </div>
      </el-form-item>

      <!-- 服务标签 -->
      <el-form-item label="服务标签：">
        <div class="service-tags-input">
          <el-input
              v-model="newTag"
              placeholder="请输入标签"
              clearable
              @keyup.enter="addTag"
          >
            <template #append>
              <el-button type="primary" @click="addTag">添加</el-button>
            </template>
          </el-input>
          <div class="tags-container">
            <el-tag
                v-for="(tag, index) in form.tags"
                :key="index"
                closable
                @close="removeTag(index)"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </el-form-item>

      <!-- 医院简介 -->
      <el-form-item label="医院简介：">
        <el-input
            v-model="form.description"
            type="textarea"
            :rows="6"
            placeholder="请输入医院简介"
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancelForm">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {router} from "@/router/index.js";

// 表单数据
const form = reactive({
  name: '',
  logo: '',
  province: '',
  city: '',
  district: '',
  street: '',
  type: '',
  level: '',
  primaryDepartments: [],
  secondaryDepartments: [],
  tags: ['在线预约', '随时退', '在线报告'],
  description: ''
})

const newTag = ref('')

// 地址选项（示例数据）
const address1 = ref([
  { value: 'bj', label: '北京市' },
  { value: 'sh', label: '上海市' },
  { value: 'gd', label: '广东省' }
])

const branchAddress1 = ref([
  { value: 'bj', label: '北京市' },
  { value: 'sh', label: '上海市' },
  { value: 'gz', label: '广州市' },
  { value: 'sz', label: '深圳市' }
])

const districts = ref([
  { value: 'xcq', label: '西城区' },
  { value: 'dcq', label: '东城区' },
  { value: 'cyq', label: '朝阳区' },
  { value: 'hdq', label: '海淀区' }
])

// 医院类型选项
const hospitalTypes = ref([
  { value: 'public', label: '公立医院' },
  { value: 'private', label: '私立医院' },
  { value: 'special', label: '专科医院' }
])

// 医院等级选项
const hospitalLevels = ref([
  { value: '3a', label: '三级甲等' },
  { value: '3b', label: '三级乙等' },
  { value: '2a', label: '二级甲等' },
  { value: '2b', label: '二级乙等' }
])

// 科室选项（示例数据）
const primaryDepartments = ref([
  { value: 'dermatology', label: '皮肤性病科' },
  { value: 'gynecology', label: '妇产科' },
  { value: 'andrology', label: '男科' },
  { value: 'pediatrics', label: '儿科' },
  { value: 'tcm', label: '中医科' },
  { value: 'psychology', label: '精神心理科' },
  { value: 'ophthalmology', label: '眼科' },
  { value: 'nutrition', label: '营养科' },
  { value: 'internal', label: '内科' },
  { value: 'dentistry', label: '口腔科' }
])

const secondaryDepartments = ref([
  { value: 'internal', label: '内科', parent: 'internal' },
  { value: 'rheumatology', label: '风湿免疫科', parent: 'internal' },
  { value: 'respiratory', label: '呼吸内科', parent: 'internal' },
  { value: 'endocrinology', label: '内分泌科', parent: 'internal' },
  { value: 'neurology', label: '神经内科', parent: 'internal' },
  { value: 'nephrology', label: '肾内科', parent: 'internal' },
  { value: 'gastroenterology', label: '消化内科', parent: 'internal' },
  { value: 'cardiology', label: '心血管内科', parent: 'internal' },
  { value: 'hematology', label: '血液内科', parent: 'internal' }
])

// 计算属性
const allPrimarySelected = computed({
  get: () => form.primaryDepartments.length === primaryDepartments.value.length,
  set: (val) => {
    form.primaryDepartments = val
        ? primaryDepartments.value.map(item => item.label)
        : []
  }
})

const allSecondarySelected = computed({
  get: () => form.secondaryDepartments.length === secondaryDepartments.value.length,
  set: (val) => {
    form.secondaryDepartments = val
        ? secondaryDepartments.value.map(item => item.label)
        : []
  }
})

const selectedPrimaryCount = computed(() => form.primaryDepartments.length)
const selectedSecondaryCount = computed(() => form.secondaryDepartments.length)

// 方法
const handleAvatarSuccess = (response, file) => {
  ElMessage.success('上传成功')
  form.logo = URL.createObjectURL(file.raw)
}

const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
  }
  return isImage && isLt2M
}

const selectAllPrimary = (val) => {
  form.primaryDepartments = val
      ? primaryDepartments.value.map(item => item.label)
      : []
}

const selectAllSecondary = (val) => {
  form.secondaryDepartments = val
      ? secondaryDepartments.value.map(item => item.label)
      : []
}

const updatePrimarySelection = () => {
  // 当取消选择一级科室时，移除对应的二级科室
  const selectedPrimaryValues = form.primaryDepartments.map(label => {
    const dept = primaryDepartments.value.find(d => d.label === label)
    return dept ? dept.value : null
  }).filter(Boolean)

  form.secondaryDepartments = form.secondaryDepartments.filter(label => {
    const dept = secondaryDepartments.value.find(d => d.label === label)
    return dept && selectedPrimaryValues.includes(dept.parent)
  })
}

const updateSecondarySelection = () => {
  // 确保选择了对应的二级科室时，其一级科室也被选中
  const selectedSecondaryParents = [...new Set(
      form.secondaryDepartments.map(label => {
        const dept = secondaryDepartments.value.find(d => d.label === label)
        return dept ? dept.parent : null
      }).filter(Boolean)
  )]

  selectedSecondaryParents.forEach(parent => {
    const primaryDept = primaryDepartments.value.find(d => d.value === parent)
    if (primaryDept && !form.primaryDepartments.includes(primaryDept.label)) {
      form.primaryDepartments.push(primaryDept.label)
    }
  })
}

const getSecondariesByPrimary = (primaryLabel) => {
  const primaryDept = primaryDepartments.value.find(d => d.label === primaryLabel)
  if (!primaryDept) return []

  return form.secondaryDepartments.filter(label => {
    const dept = secondaryDepartments.value.find(d => d.label === label)
    return dept && dept.parent === primaryDept.value
  })
}

const addTag = () => {
  if (newTag.value && !form.tags.includes(newTag.value)) {
    form.tags.push(newTag.value)
    newTag.value = ''
  }
}

const removeTag = (index) => {
  form.tags.splice(index, 1)
}

const submitForm = () => {
  ElMessage.success('提交成功！')
  console.log('表单数据:', form)
}

const cancelForm = () => {
  router.push('/hospital')
  ElMessage.info('已取消')
}
</script>

<style scoped>
.hospital-form-container {
  padding: 20px;
  background-color: #fff;
  max-width: 1000px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
  text-align: center;
}

.address-select {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.department-select {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 15px;
}

.department-level {
  margin-bottom: 20px;
}

.department-level:last-child {
  margin-bottom: 0;
}

.level-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-weight: 500;
}

.level-header > span:first-child {
  margin-right: 15px;
  font-size: 16px;
}

.selected-count {
  margin-left: 15px;
  color: #666;
  font-size: 14px;
}

.el-checkbox-group {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.selected-departments {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.selected-title {
  font-weight: 500;
  margin-bottom: 10px;
}

.service-tags-input {
  width: 100%;
}

.tags-container {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.avatar-uploader {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.upload-area {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8c939d;
}

.upload-text {
  margin-top: 8px;
  font-size: 14px;
}

.upload-hint {
  margin-top: 4px;
  font-size: 12px;
  color: #999;
}

.el-icon {
  font-size: 24px;
}
</style>